package com.douguo.recipe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.Toast;

import com.douguo.recipe.manager.Registry;
import com.douguo.recipe.manager.SharedPreferencesManager;
import com.douguo.recipe.network.Constant;
import com.douguo.recipe.network.Util;
import com.douguo.recipe.object.Caipu;
import com.douguo.recipe.object.Favor;
import com.douguo.recipe.provider.DBHelper;
import com.douguo.recipe.view.NavigationView;
import com.exchange.Controller.ExchangeDataService;
import com.exchange.Model.AdvertiserConfig;
import com.exchange.Public.ExchangeConstants;
import com.exchange.View.EmbededContainer;
import com.exchange.View.ExchangeViewManager;
import com.mobclick.android.MobclickAgent;
import com.mobclick.android.UmengFeedbackListener;

public class SettingActivity extends DouguoActivity {

	private static final String TAG = "SettingActivity";

	private static final int DIALOG_PROGRESS = 0;
	private static final int MAX_PROGRESS = 100;
	private static final int MSG_PROGRESS = 0;
	private static final int MSG_DIMISSDIALOG = 1;
	private static final int MSG_SHOWTOAST = 2;
	private static final int MSG_ARG1_SUCCESS = 0;
	private static final int MSG_ARG1_FAILURE = 1;

	private static final int MAX_FAVOR = 4;

	// --------------ui--------------
	private GridView mGridView;
	private LinearLayout mGridLinearLayout;
	private ListView mListView;
	private ProgressDialog mProgressDialog;
	private RelativeLayout mMyFavorButton;
	private NavigationView mNavigation;
	private Button mBtnFeedBack;
	private TextView mTvFavorTitle;

	// -------------dbHelper---------
	private DBHelper mDbHelper;

	// ------------adapter-----------
	private SimpleAdapter mAdapter;
	private SettingAdapter mSettingAdapter;

	// -------------data-------------
	private List<Map<String, Object>> mCaipus;
	private List<SettingItem> mSettingList;
	private List<Favor> mFavors;

	private SettingItem tools = new SettingItem();// 实用工具

	// private Thread mCheckNetworkThread;
	// private Handler mHandler = new Handler() {
	// public void handleMessage(Message msg) {
	// switch (msg.what) {
	// case MSG_PROGRESS:
	// mProgressDialog.setProgress(msg.arg1);
	// break;
	// case MSG_DIMISSDIALOG:
	//
	// break;
	// case MSG_SHOWTOAST:
	// if (msg.arg1 == MSG_ARG1_SUCCESS) {
	// Util.showShortToast(SettingActivity.this,
	// R.string.checkNetworkSuccess);
	// } else if (msg.arg1 == MSG_ARG1_FAILURE) {
	// Util.showShortToast(SettingActivity.this,
	// R.string.checkNetworkFailure);
	// }
	// break;
	// }
	// }
	// };

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting);
		mDbHelper = new DBHelper(this);
		initData();
		initUI();

	}

	@Override
	public void onResume() {
		super.onResume();
		addTools();

		updateData();
	}

	private void initUI() {
		mNavigation = new NavigationView(this, NavigationView.STATE_MORE);
		mGridView = (GridView) findViewById(R.id.setting_favor_recipe_grid);
		mTvFavorTitle = (TextView) findViewById(R.id.setting_favor_title);

		mGridView.setAdapter(mAdapter);
		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(SettingActivity.this,
						RecipeActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString("recipeId", (String) mCaipus.get(position)
						.get("favorId"));
				bundle.putInt("pos", position);
				int[] ids = new int[mCaipus.size()];
				int i = 0;
				for (; i < mCaipus.size(); ++i) {
					ids[i] = Integer.valueOf((String) mCaipus.get(i).get(
							"favorId"));
				}
				bundle.putIntArray("ids", ids);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
		mGridLinearLayout = (LinearLayout) findViewById(R.id.setting_favor_recipe_linear);
		mListView = (ListView) findViewById(R.id.setting_list);
		mListView.setAdapter(mSettingAdapter);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				SettingItem item = (SettingItem) mSettingAdapter
						.getItem(position);
				item.onClickListener.onClick(view);
			}
		});
		mMyFavorButton = (RelativeLayout) findViewById(R.id.setting_myfavor);
		mMyFavorButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(SettingActivity.this,
						FavorActivity.class));
			}
		});
		mBtnFeedBack = (Button) findViewById(R.id.setting_feedback);
		mBtnFeedBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// MobclickAgent.openFeedbackActivity(SettingActivity.this);
				Intent emailIntent = new Intent(
						android.content.Intent.ACTION_SEND);
				String[] recipients = new String[] { getString(R.string.email),
						"", };
				emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
						recipients);
				emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
						getString(R.string.version)
								+ getString(R.string.subjectEnd));
				emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "");
				emailIntent.setType("text/plain");
				startActivity(Intent.createChooser(emailIntent,
						getString(R.string.sendFeedback)));
			}
		});
		MobclickAgent.setFeedbackListener(new UmengFeedbackListener() {

			@Override
			public void onFeedbackReturned(int result) {// 0表示反馈发送成功，1表示反馈发送失败，2表示无网络连接，反馈失败。
				switch (result) {
				case 0:
					Toast.makeText(SettingActivity.this,
							R.string.feedbackSuccess, Toast.LENGTH_SHORT)
							.show();
					break;
				case 1:
					Toast.makeText(SettingActivity.this,
							R.string.feedbackFailure, Toast.LENGTH_SHORT)
							.show();
					break;
				case 2:
					Toast.makeText(SettingActivity.this,
							R.string.feedbackNetworkError, Toast.LENGTH_SHORT)
							.show();
					break;
				}

			}
		});
		findViewById(R.id.imageButton_back).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						finish();

					}
				});
		setTitle(getString(R.string.titleGengDuo));
	}

	private void initData() {
		mCaipus = new ArrayList<Map<String, Object>>();
		mSettingList = new ArrayList<SettingActivity.SettingItem>();
		// updateData();
		mAdapter = new SimpleAdapter(this, mCaipus, R.layout.setting_item,
				new String[] { "recipePic", "favorId" },
				new int[] { R.id.setting_item_img });
		mAdapter.setViewBinder(new ViewBinder() {

			public boolean setViewValue(View view, Object data,
					String textRepresentation) {
				if (view instanceof TextView) {
					TextView tv = (TextView) view;
					tv.setText(textRepresentation);
				} else if (view instanceof ImageView) {
					ImageView img = (ImageView) view;
					img.setImageBitmap((Bitmap) data);
					// img.setImageResource(R.drawable.gallery1);
				}
				return true;// must be true
			}

		});

		initSettingItems();
		mSettingAdapter = new SettingAdapter();

	}

	private void initSettingItems() {
		Registry registry = Registry.getInstance();
		final SharedPreferencesManager manager = (SharedPreferencesManager) registry
				.get(Constant.PREFERENES_MANAGER);
		boolean isUseNetwork = manager
				.getBoolean(Constant.PREFERENCES_KEY_USENETWORK);
		boolean isDownloadThumbnail = manager
				.getBoolean(Constant.PREFERENCES_KEY_DOWNLOADTHUMBNARIL);
		boolean isDownloadImage = manager
				.getBoolean(Constant.PREFERENCES_KEY_DOWNLOADIMAGE);
		final SettingItem settingNetworkItem = new SettingItem();// 设置网络

		final SettingItem aboutItem = new SettingItem();// 关于豆果

		settingNetworkItem.title = getString(R.string.setNetwork);
		settingNetworkItem.type = SettingItem.TYPE_CLICK_ACTION;
		settingNetworkItem.isSelect = isUseNetwork;
		settingNetworkItem.isEnable = true;
		settingNetworkItem.onClickListener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(SettingActivity.this,
						SettingNetworkActivity.class));
			}
		};
		aboutItem.title = getString(R.string.about_douguo);
		aboutItem.type = SettingItem.TYPE_CLICK_ACTION;
		aboutItem.onClickListener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(SettingActivity.this,
						AboutActivity.class));
			}
		};

		mSettingList.add(settingNetworkItem);
		mSettingList.add(aboutItem);

	}

	private void addTools() {
		if (ExchangeDataService.hasData() && !mSettingList.contains(tools)) {
			tools.title = getString(R.string.tools);
			tools.type = SettingItem.TYPE_CLICK_ACTION;
			tools.isEnable = true;
			tools.onClickListener = new OnClickListener() {
				@Override
				public void onClick(View view) {
//					new ExchangeViewManager().addView(getApplicationContext(),
//							(ViewGroup) findViewById(R.id.root),
//							ExchangeConstants.type_standalone_handler);
					
//					new ExchangeViewManager().addView(SettingActivity.this, ExchangeConstants.type_list_curtain);
					
//					View v = View.inflate(getApplicationContext(), R.layout.exchange_list_layout, null);
//					new EmbededContainer(SettingActivity.this, 
//							v.findViewById(R.id.ad), 
//							(ListView) v.findViewById(R.id.recipeslist), 
//							ExchangeConstants.CONTAINER_LIST_COUNT);
					
					startActivity(new Intent(SettingActivity.this, Tools2Activity.class));
				}
			};

			mSettingList.add(tools);

//			List<AdvertiserConfig> ads = ExchangeDataService.mAdvertisers;
//			for (int i = 0; i < ads.size(); i++) {
//				Log.w("Exchange ", "ads.get(i).adDescription: "
//						+ ads.get(i).adDescription);
//				Log.w("Exchange ", "ads.get(i).adDetail: "
//						+ ads.get(i).adDetail);
//				Log.w("Exchange ", "ads.get(i).adIconUrl: "
//						+ ads.get(i).adIconUrl);
//				Log.w("Exchange ", "ads.get(i).adName: " + ads.get(i).adName);
//				Log.w("Exchange ", "ads.get(i).apk: " + ads.get(i).apk);
//				Log.w("Exchange ", "ads.get(i).appkey: " + ads.get(i).appkey);
//				Log.w("Exchange ", "ads.get(i).action: " + ads.get(i).action
//						+ "");
//				Log.w("Exchange ", "ads.get(i).category: "
//						+ ads.get(i).category);
//				Log.w("Exchange ", "ads.get(i).provider: "
//						+ ads.get(i).provider);
//				Log.w("Exchange ", "ads.get(i).version: " + ads.get(i).version);
//				Log.w("Exchange ", "ads.get(i).adIcon: "
//						+ (ads.get(i).adIcon == null) + "");
//				Log.w("Exchange ", "ads.get(i).adIconIndex: "
//						+ ads.get(i).adIconIndex + "");
//				Log.w("Exchange ", "ads.get(i).fileSize: "
//						+ ads.get(i).fileSize + "");
//				Log.w("Exchange ", "ads.get(i).fullSizeBanner: "
//						+ ads.get(i).fullSizeBanner + "");
//				Log.w("Exchange ", "ads.get(i).id: " + ads.get(i).id + "");
//				Log.w("Exchange ", "ads.get(i).umengIcon: "
//						+ (ads.get(i).umengIcon == null) + "");
				
//				if (i == 0){
//					Intent intent = new Intent("android.intent.action.VIEW");
//			        intent.setDataAndType(Uri.parse(ads.get(i).apk), 
//			          "application/vnd.android.package-archive");
//			        startActivity(intent);
//				}
//			}
		}

	}

	private void updateGridWidth() {
		int width = mCaipus.size() * (60 + 5 * 2);
		mGridLinearLayout.setLayoutParams(new FrameLayout.LayoutParams(Util
				.dip2px(this, width), LayoutParams.WRAP_CONTENT));
		mGridView.setNumColumns(mCaipus.size());
	}

	private void updateData() {
		mCaipus.clear();
		mFavors = mDbHelper.getFavors();
		int i = 0;
		for (Favor favor : mFavors) {
			i = i + 1;
			if (i > MAX_FAVOR) {
				break;
			}
			Caipu caipu;
			caipu = mDbHelper.getRecipe(favor.mFavorId);
			HashMap<String, Object> hmap = new HashMap<String, Object>();
			if (caipu != null) {
				Bitmap bitmap = Util.read80X80BitmapFromSDCard(caipu.thumbPath);
				if (bitmap == null) {
					bitmap = BitmapFactory.decodeResource(getResources(),
							R.drawable.cookdefault80);
				}
				hmap.put("favorTitle", caipu.name);
				hmap.put("recipePic", bitmap);
				hmap.put("favorId", favor.mFavorId);
				mCaipus.add(hmap);
			}
		}
		mAdapter.notifyDataSetChanged();
		mTvFavorTitle.setText(getString(R.string.myCollection) + "("
				+ mFavors.size() + ")");
		updateGridWidth();
	}

	class SettingItem {
		final static int TYPE_SELECT = 0;
		// final static int TYPE_INTENT = 1;
		final static int TYPE_CLICK_ACTION = 2;
		String title;
		int type;
		boolean isSelect;
		boolean isEnable;
		Intent intent;
		OnClickListener onClickListener;
	}

	class SettingAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return mSettingList.size();
		}

		@Override
		public Object getItem(int position) {
			return mSettingList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			if (convertView == null) {
				view = LayoutInflater.from(getApplicationContext()).inflate(
						R.layout.setting_listitem, null);
			}
			TextView textView = (TextView) view
					.findViewById(R.id.setting_listitem_text);
			SettingItem settingitem = (SettingItem) getItem(position);
			textView.setText(settingitem.title);

			ImageView imgselector = (ImageView) view
					.findViewById(R.id.setting_selector);
			imgselector.setVisibility(View.INVISIBLE);

			ImageView imgArrow = (ImageView) view
					.findViewById(R.id.setting_right_arrow);
			imgArrow.setVisibility(View.INVISIBLE);

			int type = settingitem.type;
			switch (type) {
			case SettingItem.TYPE_CLICK_ACTION:// 单击动作
				imgArrow = (ImageView) view
						.findViewById(R.id.setting_right_arrow);
				imgArrow.setVisibility(View.VISIBLE);
				break;
			case SettingItem.TYPE_SELECT:// 选项:
				boolean isSelect = settingitem.isSelect;
				imgselector
						.setImageResource(isSelect == true ? R.drawable.selected
								: R.drawable.notselected);
				imgselector.setVisibility(settingitem.isEnable ? View.VISIBLE
						: View.INVISIBLE);
				imgselector.setOnClickListener(settingitem.onClickListener);
				break;
			}
			return view;
		}

	}

}
